package com.tao.aszx.manager.service.Impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tao.aszx.manager.mapper.SysUserMapper;
import com.tao.aszx.manager.service.SysUserService;
import com.tao.aszx.model.dto.system.LoginDto;
import com.tao.aszx.model.dto.system.SysUserDto;
import com.tao.aszx.model.entity.system.SysUser;
import com.tao.aszx.model.vo.system.LoginVo;
import com.tao.aszx.model.vo.common.ResultCodeEnum;
import com.tao.aszx.service.exception.CustomException;
import jakarta.annotation.Resource;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service
public class SysUserServiceImpl implements SysUserService {
    @Resource
    SysUserMapper sysUserMapper;


    @Resource
    RedisTemplate<String,String> redisTemplate;


    @Override
    public LoginVo selectSysUserByUser(LoginDto loginDto) {
        //校验验证码
        //获取输入验证码
        String inputCaptcha = loginDto.getCaptcha();
        String redisCaptcha = redisTemplate.opsForValue().get("user:login:validatecode:" + loginDto.getCodeKey());

        //验证码为空
        if (StrUtil.isEmpty(redisCaptcha) || !StrUtil.equalsIgnoreCase(redisCaptcha,inputCaptcha)){
            //没有改验证码信息
            throw new CustomException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        //使用username字段查找用户
        SysUser user = sysUserMapper.selectBySysUserName(loginDto.getUserName());

        //判断是偶查询到了用户
        if(user == null){
            //抛出用户或者密码错误的运行时异常
            throw new CustomException(ResultCodeEnum.LOGIN_ERROR);
        }

        //验证密码是否正确
        String inputPassword = loginDto.getPassword();
        String md5InputPassword = DigestUtils.md5DigestAsHex(inputPassword.getBytes());
        if(!md5InputPassword.equals(user.getPassword())) {
            throw new CustomException(ResultCodeEnum.LOGIN_ERROR);
        }

        // 生成令牌，保存数据到Redis中
        String token = UUID.randomUUID().toString().replace("-", "");

        redisTemplate.opsForValue().set("user:login:" + token, JSON.toJSONString(user) , 30 , TimeUnit.MINUTES);

        //删除redis存储的验证码数据
        redisTemplate.delete("user:login:validatecode:" + loginDto.getCodeKey());

        // 构建响应结果对象
        LoginVo loginVo = new LoginVo() ;
        loginVo.setToken(token);


        return loginVo;
    }

    @Override
    public SysUser getUserInfo(String token) {
        String UserString = redisTemplate.opsForValue().get("user:login:" + token);
        SysUser sysUser = JSON.parseObject(UserString, SysUser.class);
        return sysUser;
    }

    @Override
    public void deleteToken(String token) {
        redisTemplate.delete("user:login:" + token);
    }

    @Override
    public PageInfo<SysUser> findByPage(SysUserDto sysUserDto, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<SysUser> SysUsers = sysUserMapper.getAllSysUser(sysUserDto);
        PageInfo<SysUser> pageInfo = new PageInfo<>(SysUsers);
        return pageInfo;
    }

    @Override
    public int updateSysUser(SysUser sysUser) {
        return sysUserMapper.updateSysUser(sysUser);
    }

    @Override
    public int saveSysUser(SysUser sysUser) {
        int num=0;
        try{
             num =  sysUserMapper.saveSysUser(sysUser);
        }catch (DuplicateKeyException e) {
            return 0;
        }

            return num;
    }

    @Override
    public int deleteById(int id) {

        return sysUserMapper.deleteById(id);
    }
}
